package com.zhonghui.modlules.auth.services;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.zhonghui.common.eshopConstant.ShopConstants;
import com.zhonghui.common.eshopDomain.ShopUser;
import com.zhonghui.common.eshopEnum.AppFromEnum;
import com.zhonghui.common.eshopUtil.RedisUtils;
import com.zhonghui.common.util.IpUtil;
import com.zhonghui.modlules.auth.param.RegParam;
import com.zhonghui.modlules.shop.eshopDomain.SystemAttachment;
import com.zhonghui.modlules.shop.eshopService.SystemAttachmentService;
import com.zhonghui.modlules.user.eshopService.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Slf4j
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
@Service
public class AuthService {
    /**
     * ShopConstants.YSHOP_DEFAULT_AVATAR
     * AppFromEnum.H5.getValue()
     * StrUtil.isNotBlank
     * String.valueOf
     * ShopConstants.YSHOP_APP_LOGIN_USER
     */
    private final UserService userService;
    private final RedisUtils redisUtils;
    private final SystemAttachmentService attachmentService;


    @Transactional(rollbackFor = Exception.class)
    public void register(RegParam regParam){
        String account = regParam.getAccount();
        String ip = IpUtil.getRequestIp();
        ShopUser shopUser = ShopUser.builder()
                .username(account)
                .nickname(regParam.getNickname())
                .password(SecureUtil.md5(regParam.getPassword()))
                .phone(account)
                .avatar(ShopConstants.YSHOP_DEFAULT_AVATAR)
                .addIp(ip)
                .lastIp(ip)
                .userType(AppFromEnum.H5.getValue())
                .build();

        userService.save(shopUser);

        if (StrUtil.isNotBlank(regParam.getInviteCode())){
            SystemAttachment systemAttachment = attachmentService.getByCode(regParam.getInviteCode());
            if (systemAttachment != null){
                userService.setSpread(String.valueOf(systemAttachment.getUid()),
                        shopUser.getUid());
            }
        }
    }

    public void logout(String userName,String token){
        String key = ShopConstants.YSHOP_APP_LOGIN_USER + userName + ":" + token;
        redisUtils.del(key);
    }
}
